<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <style>
        .el-table .el-table__fixed-right {
            height: 100% !important;
        }
        .search-form .el-form-item {
            margin-bottom: 10px;
        }
        .role-management {
            padding: 20px;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .menu-tree-container {
            max-height: 400px;
            overflow: auto;
            border: 1px solid #e6e6e6;
            border-radius: 4px;
            padding: 10px;
        }
    </style>
</head>
<body>
<div id="app" class="role-management">
    <!-- 搜索区域 -->
    <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="角色名称">
            <el-input size="mini" v-model="searchForm.roleName" placeholder="请输入角色名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="权限字符">
            <el-input size="mini" v-model="searchForm.roleKey" placeholder="请输入权限字符" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="请选择状态" size="mini" clearable>
                <el-option label="正常" value="0"></el-option>
                <el-option label="停用" value="1"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button size="mini" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button size="mini" @click="resetSearch">重置</el-button>
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="handleAdd">新增角色</el-button>
        </el-form-item>
    </el-form>

    <!-- 角色列表 -->
    <el-table :data="tableData" style="width: 100%" border v-loading="loading">
        <el-table-column prop="roleId" label="角色ID" width="100" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="150" align="center"></el-table-column>
        <el-table-column prop="roleKey" label="权限字符" width="150" align="center"></el-table-column>
        <el-table-column prop="orderNum" label="显示顺序" width="100" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="80" align="center">
            <template slot-scope="scope">
                <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                        active-color="#13ce66"
                        inactive-color="#ff4949">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="100" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" align="center">
            <template slot-scope="scope">
                {{ scope.row.createTime ? formatDateTime(scope.row.createTime) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="updateBy" label="更新者" width="100" align="center"></el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="160" align="center">
            <template slot-scope="scope">
                {{ scope.row.updateTime ? formatDateTime(scope.row.updateTime) : '' }}
            </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
            <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" style="color: #f56c6c;">删除</el-button>
                <el-button size="mini" type="text" icon="el-icon-menu" @click="handleMenuAssign(scope.row)">菜单权限</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
        </el-pagination>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="600px" :close-on-click-modal="false">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="form.roleName" placeholder="请输入角色名称" maxlength="30" show-word-limit></el-input>
            </el-form-item>

            <el-form-item label="权限字符" prop="roleKey">
                <el-input v-model="form.roleKey" placeholder="请输入权限字符" maxlength="100" show-word-limit></el-input>
            </el-form-item>

            <el-form-item label="显示顺序" prop="orderNum">
                <el-input-number v-model="form.orderNum" :min="0" :max="1000" controls-position="right"></el-input-number>
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="form.status">
                    <el-radio label="0">正常</el-radio>
                    <el-radio label="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" :rows="3" placeholder="请输入备注信息" maxlength="500" show-word-limit></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 菜单权限分配对话框 -->
    <el-dialog title="菜单权限分配" :visible.sync="menuDialogVisible" width="700px">
        <div class="menu-tree-container">
            <el-tree
                    ref="menuTree"
                    :data="menuTreeData"
                    show-checkbox
                    node-key="id"
                    :props="menuProps"
                    :default-checked-keys="checkedMenuKeys"
                    style="width: 100%">
            </el-tree>
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="menuDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitMenuAssign">确定</el-button>
        </div>
    </el-dialog>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            // 校验角色名称是否唯一
            const validateRoleName = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('角色名称不能为空'));
                }
                if (value.length < 2 || value.length > 30) {
                    return callback(new Error('角色名称长度在2-30个字符之间'));
                }

                // 检查角色名称是否唯一
                axios.get('/vegetablemarketexpress/role/checkRoleNameUnique?roleName=' + value)
                    .then(response => {
                        if (response.data.code === 200) {
                            if (response.data.data && this.form.roleId !== response.data.data.roleId) {
                                callback(new Error('角色名称已存在'));
                            } else {
                                callback();
                            }
                        } else {
                            callback();
                        }
                    })
                    .catch(() => {
                        callback();
                    });
            };

            // 校验权限字符是否唯一
            const validateRoleKey = (rule, value, callback) => {
                if (!value) {
                    return callback(new Error('权限字符不能为空'));
                }
                if (value.length < 2 || value.length > 100) {
                    return callback(new Error('权限字符长度在2-100个字符之间'));
                }
                callback();
            };

            return {
                tableData: [], // 表格数据
                currentPage: 1, // 当前页码
                pageSize: 10, // 每页显示的条数
                total: 0, // 分页数据的总数
                loading: false, // 加载状态
                searchForm: {
                    roleName: '',
                    roleKey: '',
                    status: ''
                }, // 搜索条件
                title: '新增角色', // 对话框标题
                dialogFormVisible: false, // 对话框是否可见
                form: {
                    roleId: '',
                    roleName: '',
                    roleKey: '',
                    orderNum: 0,
                    status: '0',
                    remark: ''
                },
                rules: {
                    roleName: [
                        { required: true, validator: validateRoleName, trigger: 'blur' }
                    ],
                    roleKey: [
                        { required: true, validator: validateRoleKey, trigger: 'blur' }
                    ],
                    orderNum: [
                        { required: true, message: '显示顺序不能为空', trigger: 'blur' }
                    ],
                    status: [
                        { required: true, message: '请选择状态', trigger: 'change' }
                    ]
                },
                menuDialogVisible: false,
                menuTreeData: [],
                checkedMenuKeys: [],
                currentRoleId: null,
                menuProps: {
                    children: 'children',
                    label: 'label'
                }
            }
        },
        created() {
            this.loadData();
        },
        methods: {
            // 加载角色数据
            loadData() {
                this.loading = true;
                let _this = this;
                axios.post('/vegetablemarketexpress/role/queryByPage', {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                    data: this.searchForm
                }).then(function(response) {
                    _this.loading = false;
                    if (response.data.code === 200) {
                        _this.tableData = response.data.data.list;
                        _this.total = response.data.data.total;
                    } else {
                        _this.$message.error(response.data.msg || '数据加载失败');
                    }
                }).catch(function(error) {
                    _this.loading = false;
                    console.log(error);
                    _this.$message.error('数据加载失败');
                });
            },

            // 格式化日期时间
            formatDateTime(dateTime) {
                if (!dateTime) return '';
                if (typeof dateTime === 'string') {
                    return dateTime.replace('T', ' ').substring(0, 19);
                }
                return dateTime;
            },

            // 每页显示条数改变
            handleSizeChange(val) {
                this.pageSize = val;
                this.currentPage = 1;
                this.loadData();
            },

            // 当前页码改变
            handleCurrentChange(val) {
                this.currentPage = val;
                this.loadData();
            },

            // 搜索
            search() {
                this.currentPage = 1;
                this.loadData();
            },

            // 重置搜索条件
            resetSearch() {
                this.searchForm = {
                    roleName: '',
                    roleKey: '',
                    status: ''
                };
                this.currentPage = 1;
                this.loadData();
            },

            // 提交表单
            submitForm(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        let url = '/vegetablemarketexpress/role/add';
                        let successMsg = '新增成功';

                        if (this.title === '修改角色') {
                            url = '/vegetablemarketexpress/role/update';
                            successMsg = '修改成功';
                        }

                        let _this = this;
                        axios.post(url, this.form)
                            .then(function(response) {
                                if (response.data.code === 200) {
                                    _this.$message({
                                        message: successMsg,
                                        type: 'success'
                                    });
                                    _this.dialogFormVisible = false;
                                    _this.loadData();
                                } else {
                                    _this.$message.error(response.data.msg || '操作失败');
                                }
                            })
                            .catch(function(error) {
                                console.log(error);
                                _this.$message.error('操作异常');
                            });
                    } else {
                        return false;
                    }
                });
            },

            // 处理新增
            handleAdd() {
                this.dialogFormVisible = true;
                this.title = "新增角色";
                this.form = {
                    roleId: '',
                    roleName: '',
                    roleKey: '',
                    orderNum: 0,
                    status: '0',
                    remark: ''
                };

                // 清除表单验证
                if (this.$refs.form) {
                    this.$refs.form.clearValidate();
                }
            },

            // 处理编辑
            handleEdit(row) {
                this.dialogFormVisible = true;
                this.title = "修改角色";
                this.form = Object.assign({}, row);

                // 清除表单验证
                if (this.$refs.form) {
                    this.$refs.form.clearValidate();
                }
            },

            // 处理删除
            handleDelete(row) {
                this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    axios.delete('/vegetablemarketexpress/role/delete?roleId=' + row.roleId)
                        .then(function(response) {
                            if (response.data.code === 200) {
                                _this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                _this.loadData();
                            } else {
                                _this.$message.error(response.data.msg || '删除失败');
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('删除异常');
                        });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            // 处理状态改变
            handleStatusChange(row) {
                let statusText = row.status === '0' ? '启用' : '停用';
                this.$confirm('确认要' + statusText + '"' + row.roleName + '"角色吗?', '警告', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let _this = this;
                    axios.post('/vegetablemarketexpress/role/update', {
                        roleId: row.roleId,
                        roleName: row.roleName,
                        roleKey: row.roleKey,
                        status: row.status
                    }).then(function(response) {
                        if (response.data.code === 200) {
                            _this.$message({
                                message: statusText + '成功',
                                type: 'success'
                            });
                        } else {
                            _this.$message.error(response.data.msg || statusText + '失败');
                            // 恢复原状态
                            row.status = row.status === '0' ? '1' : '0';
                        }
                    }).catch(function(error) {
                        console.log(error);
                        _this.$message.error(statusText + '异常');
                        // 恢复原状态
                        row.status = row.status === '0' ? '1' : '0';
                    });
                }).catch(() => {
                    // 取消操作，恢复原状态
                    row.status = row.status === '0' ? '1' : '0';
                    this.$message({
                        type: 'info',
                        message: '已取消操作'
                    });
                });
            },

            // 打开菜单权限分配对话框
            handleMenuAssign(row) {
                this.currentRoleId = row.roleId;
                this.menuDialogVisible = true;
                this.checkedMenuKeys = [];

                // 加载菜单树和角色已有的菜单权限
                Promise.all([
                    this.loadMenuTree(),
                    this.loadRoleMenus(row.roleId)
                ]).then(() => {
                    // 设置默认选中的菜单项
                    this.$nextTick(() => {
                        if (this.$refs.menuTree) {
                            this.$refs.menuTree.setCheckedKeys(this.checkedMenuKeys);
                        }
                    });
                }).catch(error => {
                    console.error('加载菜单数据失败:', error);
                    this.$message.error('加载菜单数据失败');
                });
            },

            // 加载菜单树
            loadMenuTree() {
                return new Promise((resolve, reject) => {
                    let _this = this;
                    axios.get('/vegetablemarketexpress/menu/queryAllMenu')
                        .then(function(response) {
                            if (response.data.code === 200) {
                                _this.menuTreeData = response.data.data;
                                resolve();
                            } else {
                                _this.$message.error('加载菜单树失败');
                                reject();
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('加载菜单树异常');
                            reject();
                        });
                });
            },

            // 加载角色已有的菜单权限
            loadRoleMenus(roleId) {
                return new Promise((resolve, reject) => {
                    let _this = this;
                    axios.get('/vegetablemarketexpress/roleMenu/MenuIdsByRoleId?roleId=' + roleId)
                        .then(function(response) {
                            if (response.data.code === 200) {
                                _this.checkedMenuKeys = response.data.data;
                                resolve();
                            } else {
                                _this.$message.error('加载角色菜单权限失败');
                                reject();
                            }
                        })
                        .catch(function(error) {
                            console.log(error);
                            _this.$message.error('加载角色菜单权限异常');
                            reject();
                        });
                });
            },

            // 提交菜单权限分配
            submitMenuAssign() {
                if (!this.currentRoleId) {
                    this.$message.error('未选择角色');
                    return;
                }

                // 获取所有选中的菜单ID（包括半选中的父节点）
                const checkedKeys = this.$refs.menuTree.getCheckedKeys();
                const halfCheckedKeys = this.$refs.menuTree.getHalfCheckedKeys();
                const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];

                let _this = this;
                axios.post(`/vegetablemarketexpress/roleMenu/assignMenus?roleId=${this.currentRoleId}`, allCheckedKeys)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            _this.$message.success('菜单权限分配成功');
                            _this.menuDialogVisible = false;
                        } else {
                            _this.$message.error(response.data.msg || '菜单权限分配失败');
                        }
                    })
                    .catch(function(error) {
                        console.log(error);
                        _this.$message.error('菜单权限分配异常');
                    });
            }
        }
    });
</script>
</body>
</html>